package com.example.xianji.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.BaiKe_Adapter;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.BaiKe_List;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class Main_BaiKeActivity extends Activity implements
        BGARefreshLayoutDelegate, OnClickListener {
    private BGARefreshLayout baike_RefreshLayout;
    private ListView baike_myListview;
    private Drawable drawable;
    private EditText baike_search;
    private ArrayList<BaiKe_List> list = new ArrayList<BaiKe_List>();
    private BaiKe_Adapter mBaiKe_Adapter;
    private Button baike_set_ci;
    private AnimationDrawable animaDrawable;
    private ImageView baike_image_load, baike_search_delete;
    private RelativeLayout baike_list_back;
    private TextView baike_text_fenlei;
    private int page = 1;
    /***************** 分类id 默认0 *************************/
    public static int Cid = 0;
    /************************* 百科列表页面 **********************************/
    private String k = "";
    private ClipboardManager clipboard;
    private InputMethodManager manager;

    /***************作为选择分类的标记，初始值为0*******************************/
    public static int Choose_fenlei = 0;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                baike_myListview.setAdapter(mBaiKe_Adapter);
                animaDrawable.stop();
                baike_image_load.setVisibility(View.GONE);
                baike_RefreshLayout.endRefreshing();
            }

            if (msg.what == 2) {
                mBaiKe_Adapter.notifyDataSetChanged();
                baike_RefreshLayout.endLoadingMore();
            }

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__bai_ke);

        Cid = 0;

        baike_RefreshLayout = (BGARefreshLayout) findViewById(R.id.baike_RefreshLayout);
        baike_RefreshLayout
                .setRefreshViewHolder(new com.example.xianji.BGARefresh.BGANormalRefreshViewHolder(
                        this, true));
        baike_set_ci = (Button) findViewById(R.id.baike_set_ci);
        baike_myListview = (ListView) findViewById(R.id.baike_myListview);
        baike_search = (EditText) findViewById(R.id.baike_search);
        baike_image_load = (ImageView) findViewById(R.id.baike_image_load);
        baike_list_back = (RelativeLayout) findViewById(R.id.baike_list_back);
        baike_text_fenlei = (TextView) findViewById(R.id.baike_text_fenlei);
        baike_search_delete = (ImageView) findViewById(R.id.baike_search_delete);

        animaDrawable = (AnimationDrawable) baike_image_load.getDrawable();

        animaDrawable.start();
        baike_RefreshLayout.setDelegate(this);
        drawable = getResources().getDrawable(R.drawable.search_quan);
        drawable.setBounds(0, 0, 28, 28);
        baike_search.setCompoundDrawables(drawable, null, null, null);
        baike_search.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        baike_search_delete.setVisibility(View.GONE);

        mBaiKe_Adapter = new BaiKe_Adapter(this, list);

        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        baike_search.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    /********************* 搜索关键词 *************************/
                    k = baike_search.getText().toString();
                    Toast.makeText(Main_BaiKeActivity.this, "正在加载中....", 0).show();
                    XJApplication.cachThreadPool.execute(new Runnable() {
                        public void run() {
                            get_baike_list();
                        }
                    });
                    /***************** 隐藏键盘 ************************/
                    hideKeyboard();
                    return true;
                }
                return false;
            }
        });

        baike_search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    baike_search_delete.setVisibility(View.GONE);
                } else {
                    baike_search_delete.setVisibility(View.VISIBLE);
                }
            }
        });


        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_baike_list();
            }
        });
        baike_search_delete.setOnClickListener(this);
        baike_set_ci.setOnClickListener(this);
        baike_list_back.setOnClickListener(this);
        baike_text_fenlei.setOnClickListener(this);
    }

    /************** 百科列表数据获取 ****************************/
    public void get_baike_list() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("page", 1 + "");
        parms.addBodyParameter("cid", Cid + "");
        parms.addBodyParameter("k", k + "");
        httpUtils.send(HttpMethod.POST, Contant.baike_list, parms,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        animaDrawable.stop();
                        baike_RefreshLayout.endRefreshing();
                        baike_image_load.setVisibility(View.GONE);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        JSONObject OBJECT;
                        try {
                            OBJECT = new JSONObject(arg0.result);
                            if (OBJECT.getInt("status") == 1) {
                                list.clear();
                                JSONArray array = OBJECT.getJSONArray("data");
                                for (int i = 0; i < array.length(); i++) {
                                    BaiKe_List mBaiKe_List = new BaiKe_List();
                                    JSONObject item_object = array
                                            .getJSONObject(i);
                                    mBaiKe_List.setId(item_object.getInt("id"));
                                    mBaiKe_List.setPic(item_object
                                            .getString("pic"));
                                    mBaiKe_List.setSummary(item_object
                                            .getString("summary"));
                                    mBaiKe_List.setWord_name(item_object
                                            .getString("word_name"));
                                    list.add(mBaiKe_List);
                                }
                                handler.sendEmptyMessage(1);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    /************** 百科列表数据获取 ****************************/
    public void get_baike_list_more() {
        page++;
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("page", page + "");
        parms.addBodyParameter("cid", Cid + "");
        parms.addBodyParameter("k", k + "");

        httpUtils.send(HttpMethod.POST, Contant.baike_list, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        animaDrawable.stop();
                        baike_RefreshLayout.endLoadingMore();
                        baike_image_load.setVisibility(View.GONE);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        JSONObject OBJECT;
                        try {
                            OBJECT = new JSONObject(arg0.result);
                            if (OBJECT.getInt("status") == 1) {
                                JSONArray array = OBJECT.getJSONArray("data");
                                if (array.length() == 0) {
                                    Toast.makeText(Main_BaiKeActivity.this,
                                            "没有更多数据", 0).show();
                                    baike_RefreshLayout.endLoadingMore();
                                } else {
                                    for (int i = 0; i < array.length(); i++) {
                                        BaiKe_List mBaiKe_List = new BaiKe_List();
                                        JSONObject item_object = array
                                                .getJSONObject(i);
                                        mBaiKe_List.setId(item_object
                                                .getInt("id"));
                                        mBaiKe_List.setPic(item_object
                                                .getString("pic"));
                                        mBaiKe_List.setSummary(item_object
                                                .getString("summary"));
                                        mBaiKe_List.setWord_name(item_object
                                                .getString("word_name"));
                                        list.add(mBaiKe_List);
                                        mBaiKe_List = null;
                                    }
                                    handler.sendEmptyMessage(2);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        page = 1;
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_baike_list();
            }
        });

    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(
            BGARefreshLayout refreshLayout) {
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_baike_list_more();
            }
        });
        return true;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.baike_search_delete) {
            /*********** 删除搜索词的点击事件 ***********************/
            baike_search_delete.setVisibility(View.GONE);
            baike_search.setText("");
            k = "";
            XJApplication.cachThreadPool.execute(new Runnable() {
                public void run() {
                    get_baike_list();
                }
            });
        } else if (v.getId() == R.id.baike_set_ci) {
            /*********************** 创建词条点击 ***************************/
            startActivity(new Intent(Main_BaiKeActivity.this,
                    Main_BaiKe_SetActivity.class));
        } else if (v.getId() == R.id.baike_list_back) {

            Main_BaiKeActivity.this.finish();
        } else if (v.getId() == R.id.baike_text_fenlei) {
            /**************** 分类点击 *******************/
            /***************作为选择分类的标记，初始值为0*******************************/
            Choose_fenlei = 0;
            startActivity(new Intent(Main_BaiKeActivity.this,
                    Main_BaiKe_FenLeiActivity.class));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        /***************作为选择分类的标记，初始值为0*******************************/
        if (Choose_fenlei == 1) {
            Toast.makeText(Main_BaiKeActivity.this, "正在加载中....", 0).show();
            XJApplication.cachThreadPool.execute(new Runnable() {
                public void run() {
                    get_baike_list();
                }
            });
            Choose_fenlei = 0;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
